package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"gomicro-sharemod/services/common-service/models"
	pbParams "gomicro-sharemod/services/common-service/proto/commonParams"
	pbResult "gomicro-sharemod/services/common-service/proto/commonResult"
	pbDemo "gomicro-sharemod/services/common-service/proto/demo"
	"gomicro-sharemod/services/common-service/tools"
	"math"
	"strings"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

/*
 +----------------------------------------------------------------------
 + Title        : DemoHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2019-08-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 案例处理器
 +----------------------------------------------------------------------
*/

type DemoHandler struct {
	pbDemo.UnimplementedDemoServiceServer
}

/**
 * 新增
 *
 * @param string Hobby ------------------------必传,爱好
 * @param string Spec -------------------------必传,规格
 * @return *pbResult.Result error
 * @author huwl
 * @date 2025/11/21 13:21:32
 */
func (e *DemoHandler) AddDemo(ctx context.Context, req *pbDemo.AddDemoRequest) (*pbResult.Result, error) {
	return &pbResult.Result{Code: 200, Msg: "新增成功"}, nil
}

/**
 * 详情
 *
 * @param uint64 Id ---------------------------必传,Id
 * @return *pbDemo.Demo error
 * @author huwl
 * @date 2025/11/21 13:21:32
 */
func (e *DemoHandler) DemoDetail(ctx context.Context, req *pbParams.DetailRequest) (*pbDemo.Demo, error) {
	return &pbDemo.Demo{}, nil
}

/**
 * 列表
 *
 * @param uint64 Id ---------------------------必传,Id
 * @param string Hobby ------------------------必传,爱好
 * @param string Spec -------------------------必传,规格
 * @param string SortType ---------------------非必传,排序方式
 * @param string SortField --------------------非必传,排序字段
 * @param uint32 PageSize ---------------------非必传,条数
 * @param int32 Page --------------------------非必传,页码
 * @return *pbDemo.DemoListResponse error
 * @author huwl
 * @date 2025/11/21 13:21:32
 */
func (e *DemoHandler) DemoList(ctx context.Context, req *pbDemo.QueryDemoRequest) (*pbDemo.DemoListResponse, error) {
	params := map[string]interface{}{}

	page := req.Page
	pageSize := req.PageSize
	sortType := req.SortType
	sortField := req.SortField

	if req.Id > 0 {
		params["id"] = req.Id
	}
	if req.Ids != "" {
		params["id IN (?)"] = tools.IntSplit(strings.TrimRight(req.Ids, ","), ",")
	}
	if req.Hobby != "" {
		// 查询: ["吃饭", "睡觉", "撸猫"]
		// SELECT * FROM tour_demo WHERE JSON_CONTAINS(hobby, '["吃饭"]')
		params["JSON_CONTAINS(hobby, ?)"] = fmt.Sprintf(`["%s"]`, req.Hobby)
	}
	if req.Spec != "" {
		// 查询: {"name": "zzzz", "value": "222"}
		// 使用 ->> 操作符 (MySQL 5.7.13+)
		// Where("JSON_EXTRACT(data, '$.name') = ?", "xxxx")
		params["JSON_EXTRACT(spec, '$.name') = ?"] = req.Spec
	}
	if page <= 0 {
		page = 1
	}
	if pageSize == 0 {
		pageSize = 20
	}
	if sortField == "" {
		sortField = "id"
	}
	if sortType == "" {
		sortType = "desc"
	}

	var total int64
	err := models.Demo{}.GetTotalByParams(&models.Demo{}, &total, params)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, err.Error())
	}

	demoes := []*pbDemo.Demo{}
	if total > 0 {
		demoItems := []models.Demo{}
		err := models.Demo{}.GetResultsByParams(&models.Demo{}, &demoItems, params, int(page), int(pageSize), sortField+" "+sortType)
		if err != nil {
			return nil, status.Errorf(codes.Aborted, err.Error())
		}

		// 组装数据
		for _, demoItem := range demoItems {
			var hobby []string
			json.Unmarshal(demoItem.Hobby, &hobby)

			var spec map[string]string
			json.Unmarshal(demoItem.Spec, &spec)

			demoes = append(demoes, &pbDemo.Demo{
				Id:    uint32(demoItem.Id),
				Hobby: hobby,
				Spec:  spec,
			})
		}
	}

	pageTotal := math.Ceil(float64(total) / float64(pageSize))
	return &pbDemo.DemoListResponse{
		ListResult: &pbResult.ListCommonResult{
			Page:      page,
			Total:     uint32(total),
			PageSize:  uint32(pageSize),
			PageTotal: uint32(pageTotal),
		},
		Demoes: demoes,
	}, nil
}
